package com.fengycx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fengycx.pojo.domain.PayOrderProfitsharing;
import com.fengycx.mapper.PayOrderProfitsharingMapper;
import com.fengycx.service.IPayOrderProfitsharingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fengycx.templeate.WechatJsapiPayTemplate;
import com.wechat.pay.java.service.profitsharing.model.OrderStatus;
import com.wechat.pay.java.service.profitsharing.model.OrdersEntity;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 支付单分账表 服务实现类
 * </p>
 *
 * @author Cino
 * @since 2024-03-20
 */
@Service
public class PayOrderProfitsharingServiceImpl extends ServiceImpl<PayOrderProfitsharingMapper, PayOrderProfitsharing> implements IPayOrderProfitsharingService {

    @Autowired
    private WechatJsapiPayTemplate wechatJsapiPayTemplate;

    //定时分账
    @Override
    @XxlJob("diyName")
    public void profitSharing() {
        //分页查询状态为1 的profitSharing
        Page<PayOrderProfitsharing> page = new Page<>(1,10);
        Page<PayOrderProfitsharing> waitSharingProfits = super.page(page, new LambdaQueryWrapper<PayOrderProfitsharing>().eq(PayOrderProfitsharing::getSharingStatus, 1));
        List<PayOrderProfitsharing> sharingProfits = waitSharingProfits.getRecords();

        //查询出待分账 的账单进行 循环分账
        Date date = new Date();
        List<PayOrderProfitsharing> payOrderProfitsharings = sharingProfits.stream().filter(p -> {
            OrdersEntity sharingHandler = wechatJsapiPayTemplate.profitSharingHandler(p.getToUserOpenId(), p.getShardingAmount(), p.getPayOrderNo(), p.getTransactionId());
            OrderStatus state = sharingHandler.getState();
            if (OrderStatus.FINISHED.equals(state)) {
                p.setUpdateTime(date);
                p.setSharingStatus(2);
                return true;
            }
            return false;
        }).toList();

        super.updateBatchById(payOrderProfitsharings);
    }
}
